﻿var Logout;
var registerComplete;
var uploadAvatarComplete;
var Valid;

//Password;
var ChangePasswordComplete;
var ChangeStatusComplete;

//Image
var CropAvatarPopup;
var CropAvatarPopupComplete;
var DeleteImage;
var ImageDetail;
var uploadImagesComplete;

//Search
var ChangeSearchViewType;

//Messages
var ShowHideMessage;
var SendMessageComplete;
var DeleteConversation;
var DeleteMessage;
var SendMessagePopup;

//Report
var SendReportPopup;
var SendReportComplete;

//Comment to Admin
var SendCommentComplete;

var ClosePopup;

//Interest
var ChangeInterestViewType;
var AddFollow;
var DeleteFollow;

//Event
var ChangeNoelEvent;

// use to backup form before edit

//for blast
var oldBlast = "";

// for General
var oldName = "";
var oldSex = "";
var oldBirthDay = "";
var oldCityID = "";

//for personal
var oldHeight = "";
var oldWeight = "";
var oldReligionID = "";
var oldJobID = "";
var oldEducationID = "";
var oldIncome = "";
var oldMaritalStatusID = "";
var oldSmokingID = "";
var oldIWant = 0;
var oldHobby = "";

//for general condition
var oldCondAgeCheck;
var oldCondHeightCheck;
var oldCondWeightCheck;
var oldMinAge = "";
var oldMaxAge = "";
var oldMinHeight = "";
var oldMaxHeight = "";
var oldMinWeight = "";
var oldMaxWeight = "";
var oldCondCityID = "";
var oldCondJobID = "";
var oldCondEducationID = "";
var oldCondIncome = "";
var oldCondReligion = "";
var oldCondMaritalStatus = "";
var oldCondSmokingID = "";

//utils

//QuyBD 08/04/2010
var nct = window.nct || {};
function each(a, fn, opt_scope) {
    for (var i = 0, j = a.length; i < j; ++i) {
        fn.call(opt_scope || window, a[i], i, a);
    }
}
nct.editcontact = {

    init: function() {
        $(".btn-request").attr("disabled", false);
        $("#btnSendPassword").click(nct.editcontact.sendpassword);
        $("#changeCaptcha").click(nct.editcontact.changecaptcha);
        $("#btnChangePassword").click(nct.editcontact.changepassword);

        //paging

        var data = { url: window.location.pathname, ps: 6, pn: 1 };
        jQuery.data(document.body, "data", data);

    },

    loadallow: function(pagenum) {
        var data = jQuery.data(document.body, "data");
        if (arguments.length > 0) data.pn = pagenum;
        nct.editcontact.pagingrequestallow(data, function(response) {

            var data = jQuery.data(document.body, "data");
        });
    },
    pagingrequestallow: function(opts, cb) {

        var option = { pn: opts.pn, ps: opts.ps, ajx: true, mod: 'paging', allow: 'allow' };
        var callback = function(data) {

            jQuery("#divContentAllow").html(data);
            cb(data);
        };
        jQuery.post(opts.url, option, callback);
    },


    load: function(pagenum) {
        var data = jQuery.data(document.body, "data");
        if (arguments.length > 0) data.pn = pagenum;
        nct.editcontact.pagingrequest(data, function(response) {

            var data = jQuery.data(document.body, "data");
        });
    },
    pagingrequest: function(opts, cb) {

        var option = { pn: opts.pn, ps: opts.ps, ajx: true, mod: 'paging', allow: 'request' };
        var callback = function(data) {

            jQuery("#divContent").html(data);
            cb(data);
        };
        jQuery.post(opts.url, option, callback);
    },
    changepassword: function() {
        var password = $("#NewPassword").val();
        var confirmpassword = $("#ConfirmNewPassword").val();
        var $group = $('.change-password');
        var isValid = true;
        $group.find(':input[type!=button]').each(function(i, item) {
            if (!$(item).valid()) {
                if (isValid == true)
                    $(item).focus();
                isValid = false;
            }
        });
        if (!isValid)
            return false;
        else {
            if ($("#NewPassword").val() != $("#ConfirmNewPassword").val()) {
                jAlert(ReTypePassMissMatchError);
                return;
            }
            else {

                var UserKey = $.query.get('uid');

                $.ajax({
                    async: false,
                    dataType: 'json',
                    url: "/api/captcha.ashx",
                    type: 'POST',
                    data: {
                        type: 'changepass',
                        UserKey: UserKey,
                        NewPassWord: password,
                        ConfirmNewPassword: confirmpassword
                    },
                    success: function(msg) {

                        switch (msg.data) {
                            case '0':
                                jAlert(PasswordDeadLine);
                                return;
                            case '1':
                                jAlert(ChangePassSuccess);
                                window.location = GLOBAL_ROOT_URL;
                                return;
                            case '4':
                                jAlert(PasswordLengthError);
                                return;
                            case '5':
                                jAlert(ReTypePassMissMatchError);
                                return;
                            case '6':
                                jAlert(SystemError);
                                return;
                            case '7':
                                jAlert(ExpireDate);
                                return;
                            default:
                                return;
                        }
                    }

                });
            }
        }

    },
    changecaptcha: function() {
        $(".img-captcha").attr("src", GLOBAL_ROOT_URL + "api/captcha.ashx?rand=" + Math.random());
    },

    sendpassword: function() {
        var email = $("#Email").val();
        var txtCaptcha = $("#VerifyCaptcha").val();
        var $group = $('.forgot-password');
        var isValid = true;

        $group.find(':input').each(function(i, item) {
            if ($(item).attr("type") != "checkbox" && !$(item).valid()) {
                if (isValid == true)
                    $(item).focus();
                isValid = false;
            }
        });

        if (!isValid) {
            return false;
        }

        else {

            $.ajax({
                async: false,
                dataType: 'json',
                url: "/api/captcha.ashx",
                type: 'POST',
                data: {
                    type: 'sendpass',
                    email: email,
                    captcha: txtCaptcha
                },
                success: function(data) {
                    switch (data.status) {
                        case 'captcha':
                            jAlert(CaptchanotSame);
                            return;
                        case 'emailnotexist':
                            jAlert(EmailNotExist);
                            return;
                        case 'failed':
                            jAlert(SystemError);
                            return;
                        case 'success':
                            jAlert(RequestSentOK);
                            window.location = GLOBAL_ROOT_URL;
                            return;
                        default:
                            return;
                    }
                }

            });

        }
    },

    send: function() {

        var ReceiverUserKey = $.query.get('u');

        var SenderUserKey = $('#userLogin').text();

        var FullName = $("#FullName").text();

        jConfirm(WantToSend, Confirm, function(r) {
            if (r) {
                $.ajax({
                    async: false,
                    dataType: 'json',
                    url: "/api/usercontact.ashx",
                    type: 'POST',
                    data: {
                        type: 'request',
                        ReceiverUserKey: ReceiverUserKey,
                        SenderUserKey: SenderUserKey
                    },
                    success: function(data) {
                        switch (data.status) {
                            case 'success':
                                $('#request').hide();
                                $(".btn-request").attr("disabled", true);
                                $(".btn-request").val(SentRequest);
                                $(".btn-request").removeClass('btn-request');
                                jAlert("Yêu cầu liên lạc của bạn đã được gửi tới " + "<b>" + FullName + "</b>" + ". Bạn sẽ thấy được thông tin liên lạc ngay khi " + "<b>" + FullName + "</b>" + " đồng ý với yêu cầu của bạn.");

                                return;
                            case 'failed':
                                jAlert(SentRequest);
                                return;
                            default: //error
                                //do something
                                //Message.show("error", "Error");
                                return;
                        }
                    }

                });

            }
        });

    },

    deny: function(from, to, control) {
        jConfirm(DenyRequest, Confirm, function(r) {
            if (r) {

                $.ajax({
                    async: false,
                    dataType: 'json',
                    url: "/api/usercontact.ashx",
                    type: 'POST',
                    data: {
                        type: 'deny',
                        SenderUserKey: from,
                        ReceiverUserKey: to
                    },
                    success: function(data) {
                        switch (data.status) {
                            case 'success':
                                $(control).closest('.search-thumb-box').remove();
                                //jAlert("Đã từ chối thành công.");
                                if ($('#divContent .search-thumb-box').length < 1) {

                                    $(" #divContent .content").html('<div class="empty-page">Bạn không có yêu cầu xem thông tin liên hệ.</div>');
                                }

                                var request = $("#requestDelay .Allli_select").text();

                                if (request === undefined || request.length === 0) {
                                    nct.editcontact.load(1);
                                } else {
                                    if ($('#divContent .search-thumb-box').length === 0) {
                                        nct.editcontact.load(1);
                                    }
                                    else {
                                        nct.editcontact.load(request);
                                    }

                                }

                                return;
                            case 'failed':
                                jAlert(NotDenyRequest);
                                return;
                            default: //error
                                //do something
                                //Message.show("error", "Error");
                                return;
                        }
                    }

                });

            }
        });
    },
    allow: function(from, to, control) {

    jConfirm(Question, Confirm, function(r) {
            if (r) {

                $.ajax({
                    async: false,
                    dataType: 'json',
                    url: "/api/usercontact.ashx",
                    type: 'POST',
                    data: {
                        type: 'allow',
                        SenderUserKey: from,
                        ReceiverUserKey: to
                    },
                    success: function(data) {
                        switch (data.status) {
                            case 'success':
                                $(control).closest('.search-thumb-box').remove();

                                var allow = $("#allowDelay .Allli_select").text();

                                var request = $("#requestDelay .Allli_select").text();

                                if (request === undefined || request.length === 0) {
                                    nct.editcontact.load(1);
                                } else {
                                    if ($(' #divContent .search-thumb-box').length === 0) {
                                        nct.editcontact.load(1);
                                    }
                                    else {
                                        nct.editcontact.load(request);
                                    }
                                }
                                if (allow === undefined || allow.length === 0) {
                                    nct.editcontact.loadallow(1);
                                } else {
                                    if ($(' #divContentAllow .search-thumb-box').length === 0) {
                                        nct.editcontact.loadallow(1);
                                    }
                                    else {
                                        nct.editcontact.loadallow(allow);
                                    }
                                }
                                return;
                            case 'failed':
                                jAlert(CanNotUpdateRequest);
                                return;
                            default: //error
                                //do something
                                //Message.show("error", "Error");
                                return;
                        }
                    }

                });

            }
        });
    },
    remove: function(from, to, control) {

//    var length = $(' #divContentAllow .search-thumb-box').length;
//    alert(length);
    jConfirm(QuestionDelete, Confirm, function(r) {
            if (r) {
                $.ajax({
                    async: false,
                    dataType: 'json',
                    url: "/api/usercontact.ashx",
                    type: 'POST',
                    data: {
                        type: 'delete',
                        SenderUserKey: from,
                        ReceiverUserKey: to
                    },
                    success: function(data) {
                        switch (data.status) {
                            case 'success':

                                $(control).closest('.search-thumb-box').remove();

                                var allow = $("#allowDelay .Allli_select").text();
                                
                                if (allow === undefined || allow.length === 0) {
                                    nct.editcontact.loadallow(1);
                                } else {

                              
                                if ($(' #divContentAllow .search-thumb-box').length === 0) {
                                        nct.editcontact.loadallow(1);
                                    }
                                    else {
                                        nct.editcontact.loadallow(allow);
                                    }
                                }
                                return;
                            case 'failed':
                                jAlert('Không thể xóa được.');
                                return;
                            default: //error
                                //do something
                                //Message.show("error", "Error");
                                return;
                        }
                    }

                });


            }
        });
    }
};

$(function() {
    nct.editcontact.init();
});
var createCookie, readCookies;

$(document).ready(function() {

    jQuery("span.timeago").timeago();

    $("#email_login").focus();

    $("#ReplyContent").focus();

    if ($("#email_cs").attr('id') == "email_cs") {
        $("#frmmain").attr("onsubmit", "return false;");
    }

    $('input,select,textarea').focus(function() {
        $(this).addClass("itemfocus");
    });
    $('input,select,textarea').blur(function() {
        $(this).removeClass("itemfocus");
    });

    Shadowbox.init({
        players: ["html", "iframe"],
        overlayOpacity: 0.4,
        handleOversize: "resize"
    });

    //Thỏa thuận sử dụng VISS
    $("#ruleVISS").click(function() {
        Shadowbox.open({
            player: "iframe",
            content: GLOBAL_ROOT_URL + 'tpl/rule.html',
            //title: $(this).attr("title"), 
            height: "500",
            width: "700"
        });
    });

    //Hỗ trợ lý do không được duyệt
    $("#ruleVerify").click(function() {
        Shadowbox.open({
            player: "iframe",
            content: GLOBAL_ROOT_URL + 'tpl/help.html',
            //title: $(this).attr("title"), 
            height: "500",
            width: "717"
        });
    });

    //Góp ý cho quản trị viên
    $("#commentToAdmin").click(function() {
        Shadowbox.open({
            player: "iframe",
            content: GLOBAL_ROOT_URL + 'cm',
            //title: $(this).attr("title"), 
            height: "260",
            width: "500"
        });
    });

    //File Browse for avatar
    $("#Avatar").filestyle({
        image: GLOBAL_RESOURCES_PATH + "/images/button-browse.jpg",
        imageheight: 25,
        imagewidth: 80,
        width: 160
    });

    //File Browse for Image
    $("#Image1").filestyle({
        image: GLOBAL_RESOURCES_PATH + "/images/button-browse.jpg",
        imageheight: 25,
        imagewidth: 80,
        width: 280
    });

    // tương tác cho tab profile.
    $(document.body).tabs({
        idtab: '#tab-nav-profile > ul > li > a',
        idtarget: '#tab-nav-profile-target .tab-target'
    });

    //Limit character for Blast
    $('#textarea-blast').charCounter(BlastLimit, {
        container: '<span></span>',
        classname: 'grey',
        format: '',
        pulse: false,
        delay: 1
    });

    //Limit character for AboutMe
    $('#Introduce').charCounter(BlastLimit, {
        container: '<span></span>',
        classname: 'grey',
        format: '',
        pulse: false,
        delay: 1
    });

    //Limit character for Hobby
    $('#txtHobby').charCounter(HobbyLimit, {
        container: '<span></span>',
        classname: 'grey',
        format: '',
        pulse: false,
        delay: 1
    });

    //Limit character for Reply Message
    $('#ReplyContent').charCounter(MessageContentLimit, {
        container: '<span></span>',
        classname: 'grey',
        format: '',
        pulse: false,
        delay: 1
    });

    //DatePicker For Register
    var BeginDate = DateAdd('y', new Date(), -MaxAge);
    var EndDate = DateAdd('y', new Date(), -MinAge);

    $('.date-pick').datePicker({
        clickInput: false,

        startDate: '01/01/' + BeginDate.getFullYear(),
        endDate: "31/12/" + EndDate.getFullYear()
    });

    //Logout
    Logout = function() {
        $.post('/api/user.ashx', { action: 'logout' }, function(data) {
            if (data.result = "1") {
                window.location = "/home";
            }
        });
    };

    //begin: Changed value checkbox when click
    $("#IwantMale").click(function() {
        if ($(this).is(':checked'))
            $(this).val("1");
        else
            $(this).val("0");
    });

    $("#IwantFemale").click(function() {
        if ($(this).is(':checked'))
            $(this).val("1");
        else
            $(this).val("0");
    });
    //end: Changed value checkbox when click

    //Hint ComingSoon
    $('#email_cs').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'left',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#accept').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'left',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    //Hint Login
    $('#email_login').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#password').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    //Hint Register
    $('#Fullname').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#Birthday').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 40,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#SexMale').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 210,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#SexFemale').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 130,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#Job').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#Email').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#VerifyEmail').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#Phone').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    $('#Introduce').poshytip({
        className: 'tip-twitter',
        showOn: 'focus',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        allowTipHover: false,
        fade: true,
        slide: true
    });

    /*** begin: Login   ***/
    $("#login-page #btnDangNhap").click(function(evt) {
        ValidateAndSubmitLogin(evt);
    });
    $("#login-page input").keydown(function(evt) {
        // Only execute validation if the key pressed was enter.
        if (evt.keyCode == 13) {
            ValidateAndSubmitLogin(evt);
        }
    });

    /*** end: Login   ***/

    /*** begin: ComingSoon   ***/

    $("#email_cs").css("font-size", "12px");
    $("#email_cs").css("color", "#989898");
    $("#email_cs").val(hintEmailCS);

    $("#email_cs").focus(function() {
        if ($(this).val() == hintEmailCS) {
            $(this).css("font-size", "13px");
            $(this).css("color", "#343434");
            $(this).val("");
        }
    });

    $("#email_cs").blur(function() {
        if ($(this).val() == "") {
            $(this).css("font-size", "12px");
            $(this).css("color", "#989898");
            $(this).val(hintEmailCS);
        }
    });

    $(".comingsoon #btnJoinEmail").click(function(evt) {
        ValidateAndSubmitComingSoon(evt);
    });
    $(".comingsoon input").keydown(function(evt) {

        // Only execute validation if the key pressed was enter.
        if (evt.keyCode == 13) {
            ValidateAndSubmitComingSoon(evt);
        }
    });
    /*** end: ComingSoon   ***/

    /*** begin: Register   ***/

    //suggestion for input Fullname
    $("#Fullname").css("font-size", "11px");
    $("#Fullname").css("color", "#989898");
    $("#Fullname").val(hintFullName);

    $("#Fullname").focus(function() {
        if ($(this).val() == hintFullName) {
            $(this).css("font-size", "13px");
            $(this).css("color", "#343434");
            $(this).val("");
        }
    });

    $("#Fullname").blur(function() {
        if ($(this).val() == "") {
            $(this).css("font-size", "11px");
            $(this).css("color", "#989898");
            $(this).val(hintFullName);
        }
    });

    //suggestion for input datepicker
    $("#Birthday").css("font-size", "11px");
    $("#Birthday").val(hintBirthday);
    $("#Birthday").css("color", "#989898");

    $("#Birthday").focus(function() {
        if ($(this).val() == hintBirthday) {
            $(this).css("font-size", "13px");
            $(this).css("color", "#343434");
            $(this).val("");
        }
    });

    $("#Birthday").change(function() {
        if ($(this).val() != hintBirthday) {
            $(this).css("font-size", "13px");
            $(this).css("color", "#343434");
        }
    });

    $("#Birthday").blur(function() {
        if ($(this).val() == "") {
            $(this).css("font-size", "11px");
            $(this).val(hintBirthday);
            $(this).css("color", "#989898");
        }
    });

    //begin: Event Submit For Register
    $("#register-box input").keydown(function(e) {
        if (e.which == 13) {
            $("#btnSubmit").click();
        }
    });

    $("#register-box select").keydown(function(e) {
        if (e.which == 13) {
            $("#btnSubmit").click();
        }
    });
    $("#register-box #btnSubmit").click(function(evt) {
        ValidateAndSubmitRegister(evt);
    });

    //end: Event Submit For Register

    registerComplete = function(result) {
        if (result == "success") {
            window.location = "/ms";
        }
        else if (result == "Exist") {
            jAlert(EmailExisted);
            $("#btnSubmit").show();
            $("#ajaxloader").remove();
        }
        else if (result == "Unknown" || result == "fail") {
            jAlert("Lỗi hệ thống. Vui lòng liên hệ Admin");
            $("#btnSubmit").show();
            $("#ajaxloader").remove();
        }
        else {
            jAlert(result);
            $("#btnSubmit").show();
            $("#ajaxloader").remove();
        }
    };
    /*** end: Register   ***/

    /*** begin: Password   ***/

    $("#change-password").click(function() {
        Shadowbox.open({
            player: "iframe",
            content: GLOBAL_ROOT_URL + 'profile/password',
            //title: $(this).attr("title"), 
            height: "200",
            width: "408"
        });
    });

    ChangePasswordComplete = function(result) {
        if (result == "-1") {
            window.location = "/login";
            return;
        }
        if (result == "1") {
            jAlert(ChangePassSuccess);
            Shadowbox.close();
        }
    };
    ChangeStatusComplete = function(result) {
        if (result == "-1") {
            window.location = "/login";
            return;
        }
        if (result == "1") {
            jAlert(ChangeStatusCompletes);
            Shadowbox.close();
        }
    };

    /*** end: Password   ***/

    /*** begin: Avatar   ***/
    $("#avatar-box").hover(
        function() {
            $("#change-avatar").css("display", "block");
        }, function() {
            $("#change-avatar").css("display", "none");
        });

    $("#change-avatar").click(function() {
        Shadowbox.open({
            player: "iframe",
            content: GLOBAL_ROOT_URL + 'profile/avatar',
            //title: $(this).attr("title"), 
            height: "170",
            width: "420"
        });
    });

    uploadAvatarComplete = function(result, imagePath) {
        if (result == "-1") {
            window.location = "/login";
            return;
        }
        if (result == "1") {
            $("#avatar").html("<img src='" + imagePath + "' />");
        }
        else {
            jAlert(ImageUploadError);
        }
        Shadowbox.close();
    };

    /*** end: Avatar   ***/

    /*** begin: Blast   ***/
    //Blast
    $("#edit-blast").click(function() {
        $("#body-content").hide();
        $("#body-edit").show();
        $("#body-edit").attr("style", "padding: 0 10px; width: 386px;");
        $("#body-edit .blast-text").attr("style", "padding-bottom: 0px;");
        oldBlast = $("#textarea-blast").val();
    });

    $("#cancel-blast").click(function() {
        $("#body-edit").hide();
        $("#body-content").show();
        $("#textarea-blast").val(oldBlast);
    });

    $("#save-blast").click(function() {
        if ($("#textarea-blast").val().length < 1 || $("#textarea-blast").val().length > BlastLimit) {
            jAlert(BlastError);
            return;
        }
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/user.ashx",
            type: 'POST',
            data: {
                action: 'saveBlast',
                content: $("#textarea-blast").val()
            },
            success: function(data) {
                if (data.result == "-1")
                    jAlert(LoginRequired);
                else if (data.result == "0")
                    jAlert(SystemError);
                else if (data.result == "2")
                    jAlert(BlastError);
                else if (data.result == "3")
                    jAlert(BlastNotAppropriateError);
                else if (data.result == "1") {
                    $("#blast-text").html($("#textarea-blast").val());
                    $("#body-edit").hide();
                    $("#body-content").show();
                }
            }
        });
    });
    /*** end: Blast   ***/

    /*** begin: General   ***/

    //suggestion for input Fullname
    $("#EditFullname").css("font-size", "11px");
    $("#EditFullname").css("color", "#989898");
    $("#EditFullname").val(hintFullName);

    $("#EditFullname").focus(function() {
        if ($(this).val() == hintFullName) {
            $(this).css("font-size", "13px");
            $(this).css("color", "#343434");
            $(this).val("");
        }
    });

    $("#EditFullname").blur(function() {
        if ($(this).val() == "") {
            $(this).css("font-size", "11px");
            $(this).css("color", "#989898");
            $(this).val(hintFullName);
        }
    });

    //suggestion for input datepicker
    $("#EditBirthday").css("font-size", "11px");
    $("#EditBirthday").css("color", "#989898");

    $("#EditBirthday").focus(function() {
        if ($(this).val() == hintBirthday) {
            $(this).css("font-size", "13px");
            $(this).css("color", "#343434");
            $(this).val("");
        }
    });

    $("#EditBirthday").change(function() {
        if ($(this).val() != hintBirthday) {
            $(this).css("font-size", "13px");
            $(this).css("color", "#343434");
        }
    });

    $("#EditBirthday").blur(function() {
        if ($(this).val() == "") {
            $(this).css("font-size", "11px");
            $(this).val(hintBirthday);
            $(this).css("color", "#989898");
        }
    });

    $("#edit-general").click(function() {
        oldName = $("#EditFullName").val();
        oldBirthDay = $("#EditBirthday").val();
        if ($("#EditSexMale").attr("checked") != "") {
            oldSex = "1";
        }
        else {
            oldSex = "0";
        }
        oldCityID = $("#EditCity").val();
        $("#account-box").hide();
        $("#account-box-edit").show();
    });

    $("#cancel-general").click(function() {
        $("#account-box").show();
        $("#account-box-edit").hide();
        $("#EditFullName").val(oldName);
        if (oldSex == "1") {
            $("#EditSexMale").attr("checked", "checked");
        }
        else {
            $("#EditSexFemale").attr("checked", "checked");
        }
        $("#EditBirthday").val(oldBirthDay);
        $("#EditCity").val(oldCityID);
    });

    $("#account-box-edit #save-general").click(function(evt) {
        ValidateAndSubmitGeneral(evt);
    });

    /*** end: General   ***/

    /*** begin: Personal   ***/
    //Personal
    $("#edit-personal").click(function() {
        oldHeight = $("#txtHeight").val();
        oldWeight = $("#txtWeight").val();
        oldReligionID = $("#Religion").val();
        oldJobID = $("#Job").val();
        oldEducationID = $("#Education").val();
        oldIncome = $("#Income").val();
        oldMaritalStatusID = $("#MaritalStatus").val();
        oldSmokingID = $("#Smoking").val();
        if ($("#IwantMale").attr("checked") != "" && $("#IwantFemale").attr("checked") != "") {
            oldIWant = 2;
        }
        else if ($("#IwantMale").attr("checked") != "") {
            oldIWant = 1;
        }
        else if ($("#IwantFemale").attr("checked") != "") {
            oldIWant = 0;
        }
        oldHobby = $("#txtHobby").val();
        $("#personal-field").hide();
        $("#personal-edit").show();
    });

    $("#cancel-personal").click(function() {
        $("#personal-field").show();
        $("#personal-edit").hide();
        $("#txtHeight").val(oldHeight);
        $("#txtWeight").val(oldWeight);
        $("#Religion").val(oldReligionID);
        $("#Job").val(oldJobID);
        $("#Education").val(oldEducationID);
        $("#Income").val(oldIncome);
        $("#MaritalStatus").val(oldMaritalStatusID);
        $("#Smoking").val(oldSmokingID);
        if (oldIWant == 2) {
            $("#IwantMale").attr("checked", "checked");
            $("#IwantMale").val(1);
            $("#IwantFemale").attr("checked", "checked");
            $("#IwantFemale").val(1);
        }
        else if (oldIWant == 1) {
            $("#IwantMale").attr("checked", "checked");
            $("#IwantMale").val(1);
            $("#IwantFemale").removeAttr("checked");
            $("#IwantFemale").val(0);
        }
        else if (oldIWant == 0) {
            $("#IwantFemale").attr("checked", "checked");
            $("#IwantFemale").val(1);
            $("#IwantMale").removeAttr("checked");
            $("#IwantMale").val(0);
        }
        $("#txtHobby").val(oldHobby);
    });

    $("#personal-edit #save-personal").click(function(evt) {
        ValidateAndSubmitPersonal(evt);
    });

    //end: Personal

    //begin: General Condition

    $("#edit-general-condition").click(function() {
        oldMinAge = $("#txtOldMin").val();
        oldMaxAge = $("#txtOldMax").val();
        oldMinHeight = $("#txtHeightMin").val();
        oldMaxHeight = $("#txtHeightMax").val();
        oldMinWeight = $("#txtWeightMin").val();
        oldMaxWeight = $("#txtWeightMax").val();
        oldCondCityID = $("#CoditionCity-1").val();
        oldCondJobID = $("#CoditionJob-1").val();
        oldCondEducationID = $("#CoditionEducation").val();
        oldCondIncome = $("#CoditionIncome").val();
        oldCondReligion = $("#CoditionReligion").val();
        oldCondMaritalStatus = $("#CoditionMaritalStatus").val();
        oldCondSmokingID = $("#CoditionSmoking").val();

        $("#general-condition-edit").show();
        $("#general-condition-field").hide();
    });

    $("#cancel-general-condition").click(function() {
        $("#general-condition-edit").hide();
        $("#general-condition-field").show();

        $("#txtOldMin").val(oldMinAge);
        $("#txtOldMax").val(oldMaxAge);

        $("#txtHeightMin").val(oldMinHeight);
        $("#txtHeightMax").val(oldMaxHeight);

        $("#txtWeightMin").val(oldMinWeight);
        $("#txtWeightMax").val(oldMaxWeight);

        $("#CoditionCity-1").val(oldCondCityID);
        $("#CoditionJob-1").val(oldCondJobID);
        $("#CoditionEducation").val(oldCondEducationID);
        $("#CoditionIncome").val(oldCondIncome);
        $("#CoditionReligion").val(oldCondReligion);
        $("#CoditionMaritalStatus").val(oldCondMaritalStatus);
        $("#CoditionSmoking").val(oldCondSmokingID);

    });

    $("#save-general-condition").click(function(evt) {
        ValidateAndSubmitGeneralCondition(evt);

    });
    //end: General Condition



    //begin : Contact
    //edit contact
    $("#edit-contact").click(function() {

        $("#contact-edit").show();
        $("#contact-field").hide();

    });

    //cancel update
    $("#cancel-contact").click(function() {

        $("#contact-edit").hide();
        $("#contact-field").show();

    });
    //cancel update


    $("#save-contact").click(function(evt) {

        var email = $("#txtEmail").val();
        var homephone = $("#txtHomePhone").val();
        var mobile = $("#txtMobile").val();
        var address = $("#txtAddress").val();
        var $group = $('#contact-edit');
        var isValid = true;

        $group.find(':input').each(function(i, item) {
            if ($(item).attr("type") != "checkbox" && !$(item).valid()) {
                if (isValid == true)
                    $(item).focus();
                isValid = false;
            }
        });

        if (!isValid)
            evt.preventDefault();

        else {
            //alert(email);
            $.ajax({
                async: false,
                dataType: 'json',
                url: "/api/usercontact.ashx",
                type: 'POST',
                data: {
                    type: 'update',
                    email: email,
                    homephone: homephone,
                    mobile: mobile,
                    address: address
                },
                success: function(data) {
                    switch (data.status) {
                        case 'success':
                            if (email === undefined || email.length === 0) {
                                $("#field-email").text('Chưa cung cấp');
                            }
                            else {
                                $("#field-email").text(email);
                            }
                            if (homephone === undefined || homephone.length === 0) {
                                $("#field-homephone").text('Chưa cung cấp');
                            }
                            else {
                                $("#field-homephone").text(homephone);
                            }
                            if (mobile === undefined || mobile.length === 0) {
                                $("#field-mobile").text('Chưa cung cấp');
                            }
                            else {
                                $("#field-mobile").text(mobile);
                            }
                            if (address === undefined || address.length === 0) {
                                $("#field-address").text('Chưa cung cấp');
                            }
                            else {
                                $("#field-address").text(address);
                            }
                            //alert(data.status);
                            $("#contact-edit").hide();
                            $("#contact-field").show();
                            return;
                        case 'error':
                            jAlert('error');
                            return;
                        case 'failed':
                            jAlert('failed');
                            return;
                        default: //error
                            //do something
                            //Message.show("error", "Error");
                            return;
                    }
                }

            });
        }

    });


    //update contact
    //end : Contact
    /*** begin: Upload Image   ***/

    $("#add-more-file").click(function() {
        NumberOfImages += 1;
        $("#upload-fields").append("<div class='upload-field'>Hình " + NumberOfImages + ": <input type='file' class='input-file' id='Image" + NumberOfImages + "' name='Image" + NumberOfImages + "' /></div>");
        $("#Image" + NumberOfImages).filestyle({
            image: GLOBAL_RESOURCES_PATH + "/images/button-browse.jpg",
            imageheight: 25,
            imagewidth: 80,
            width: 280
        });
        if (NumberOfImages == 5) {
            $("#add-more").hide();
        }
    });

    $("#btn-Upload").click(function() {
        var hasfile = 0;
        for (i = 1; i <= NumberOfImages; i++) {
            if ($("#Image" + i).val() != "")
                hasfile += 1;
        }
        if (hasfile == 0) {
            jAlert(ImagesRequired);
            return;
        }
        var refesh = new Date();
        $("#frmmain").attr("action", "/api/user.ashx?" + refesh.getMilliseconds());
        $("#frmmain").attr("method", "post");
        $("#frmmain").attr("target", "UploadWindow");
        $("#frmmain").attr("enctype", "multipart/form-data");
        $("#frmmain").attr("encoding", "multipart/form-data");
        $("#action-request").attr("name", "action");

        $("#btn-Upload").hide();
        $("#btn-Upload").parent().prepend("<img id=\"ajaxloader\" style=\"padding-top:10px;\" src=\"" + GLOBAL_RESOURCES_PATH + "/images/ajax-loader.gif\" alt=\"đang upload hình\" />");
        $("#frmmain").submit();
    });

    uploadImagesComplete = function(result) {
        if (result == "-1") {
            window.location = "/login";
            return;
        }
        if (result == "0") {
            jAlert(ImagesRequired);
            $("#btn-Upload").show();
            $("#ajaxloader").remove();
            return;
        }
        if (result == "-2") {
            jAlert(SystemError);
            return;
        }
        window.location = "/profile/images";
    };

    /***end: Upload Image ***/

    /*** begin: Crop Avatar Popup ***/

    function getCenteredCoords(width, height) {
        var xPos = null;
        var yPos = null;
        if (window.ActiveXObject) {
            xPos = window.event.screenX - (width / 2) + 100;
            yPos = window.event.screenY - (height / 2) - 100;
        } else {
            var parentSize = [window.outerWidth, window.outerHeight];
            var parentPos = [window.screenX, window.screenY];
            xPos = parentPos[0] + Math.max(0, Math.floor((parentSize[0] - width) / 2));
            yPos = parentPos[1] + Math.max(0, Math.floor((parentSize[1] - (height * 1.25)) / 2));
        }
        return [xPos, yPos];
    };

    CropAvatarPopup = function(imageID) {
        var cropAvatarPopupWindow = window.open(GLOBAL_ROOT_URL + 'profile/cropavatar?iid=' + imageID, 'CropAvatarPopup', "width=650, height=700, location=1, status=1, resizable=yes");
        var coords = getCenteredCoords(650, 700);
        cropAvatarPopupWindow.moveTo(coords[0], coords[1]);
        cropAvatarPopupWindow.focus();
    };

    CropAvatarPopupComplete = function(result) {
        if (result == "-1") {
            window.location = GLOBAL_ROOT_URL + 'login';
        }
        if (result == "-2") {
            jAlert(ImageNotExisted);
            return;
        }
        if (result == "1") {
            jAlert("Nạp tiền đi mày");
        }
    }

    /***end: Crop Avatar Popup ***/

    /*** begin: Delete Image   ***/

    DeleteImage = function(imageId) {
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/user.ashx",
            type: 'POST',
            data: {
                action: "deleteImage",
                id: imageId
            },
            success: function(data) {
                if (data.result == "-1") {
                    window.location = '/login';
                    return;
                }
                else if (data.result == "0") {
                    jAlert(SystemError);
                    return;
                }
                window.location = "/profile/" + $("#Target").val() + "?p=" + $("#Page").val();
            }
        });
    };

    ImageDetail = function(imageId, userKey) {
        if (userKey != "") {
            window.location = '/profile/album?u=' + userKey + '&k=' + imageId + "&p=" + $("#Page").val();
        }
        else {
            window.location = '/profile/album?k=' + imageId + "&p=" + $("#Page").val();
        }
    };

    //end: Delete Image

    //begin: Crop Image
    var api;
    $("#btn-Choose-Avatar").click(function() {
        api = $.Jcrop('#cropbox', {
            onChange: cropImage,
            onSelect: cropImage,
            onFailSelect: function() { jAlert(CropSizeError); }
        });
        $("#btn-Choose-Done").show();
        $("#btn-Choose-Cancel").show();
        $("#image-box-tip").show();
        $("#btn-Choose-Avatar").hide();
    });

    $("#btn-Choose-Cancel").click(function() {
        api.destroy();
        $("#btn-Choose-Avatar").show();
        $("#image-box-tip").hide();
        $("#btn-Choose-Done").hide();
        $("#btn-Choose-Cancel").hide();
    });

    $("#btn-Choose-Done").click(function() {
        var x, y, w, h;
        x = parseInt($("#x").val());
        y = parseInt($("#y").val());
        w = parseInt($("#w").val());
        h = parseInt($("#h").val());
        if (w == 0 || h == 0) {
            jAlert(CropError);
            return;
        }
        if (parseFloat(w) / parseFloat(h) > parseFloat(1.9)) {
            jAlert(CropRateError);
            return;
        }
        else if (parseInt(w) < 210 || parseInt(h) < 120) {
            jAlert(CropSizeError);
            return;
        }
        $("#btn-Choose-Done").parent().prepend("<img id=\"ajaxloader\" style=\"padding-top:10px;float:right;\" src=\"" + GLOBAL_RESOURCES_PATH + "/images/ajax-loader.gif\" alt=\"đang tải\" />");
        $("#btn-Choose-Done").hide();
        $("#btn-Choose-Cancel").hide();
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/user.ashx",
            type: 'POST',
            data: {
                action: "changeAvatarByImage",
                id: $("#imageId").val(),
                x: x,
                y: y,
                w: w,
                h: h
            },
            success: function(data) {
                $("#ajaxloader").remove();
                if (data.result == "-1") {
                    window.location = "/login";
                    return;
                }
                if (data.result == "0") {
                    $("#btn-Choose-Done").show();
                    $("#btn-Choose-Cancel").show();
                    jAlert(SystemError);
                    return;
                }
                if (data.result == "2") {
                    $("#btn-Choose-Done").show();
                    $("#btn-Choose-Cancel").show();
                    jAlert(CropSizeError);
                    return;
                }
                if (data.result == "3") {
                    jAlert(CropRateError);
                    return;
                }
                if (data.result == "1") {
                    jAlert(CropSuccessMsg);
                    api.destroy();
                    $("#image-box-tip").hide();
                    $("#btn-Choose-Avatar").show();
                }
            }
        });
    });

    function cropImage(coords) {
        if (parseInt(coords.w) > 0) {
            var rx = 100 / coords.w;
            var ry = 100 / coords.h;

            $('#x').val(coords.x);
            $('#y').val(coords.y);
            $('#w').val(coords.w);
            $('#h').val(coords.h);
        }
    };

    /*** begin: Search   ***/

    $("#search-box input").keydown(function(evt) {
        // Only execute validation if the key pressed was enter.
        if (evt.keyCode == 13) {
            //$(".tip-twitter").remove();
            $("#btn-Search").click();
        }
    });

    $("#search-box select").keydown(function(evt) {
        // Only execute validation if the key pressed was enter.
        if (evt.keyCode == 13) {
            //$(".tip-twitter").remove();
            $("#btn-Search").click();
        }
    });

    $("#btn-SearchHome").click(function(evt) {
        var $group = $("#search-form");
        var isValid = true;
        var count = 0;
        $group.find(':input[type!=button]').each(function(i, item) {
            if (!$(item).valid()) {
                if (isValid == true) {
                    $(item).focus();
                }
                isValid = false;
            }
        });
        if (!isValid)
            evt.preventDefault();
        else {
            var url = GLOBAL_ROOT_URL + "guest/search?";

            if ($("#SearchGenderMale").is(':checked') || $("#SearchGenderFemale").is(':checked')) {
                if ($("#SearchGenderMale").is(':checked'))
                    url += "gender=1";
                else
                    url += "gender=0";
                count++;
            }
            if ($("#SearchCity :selected").val() != -1) {
                if (count > 0) {
                    url += "&";
                }
                url += "city=" + $("#SearchCity :selected").val();
                count++;
            }
            if ($("#SearchFromAge").val() != "") {
                if (count > 0) {
                    url += "&";
                }
                url += "fromage=" + $("#SearchFromAge").val();
                count++;
            }
            if ($("#SearchToAge").val() != "") {
                if (count > 0) {
                    url += "&";
                }
                url += "toage=" + $("#SearchToAge").val();
                count++;
            }
            window.location = url;
        }
    });

    $("#btn-Search").click(function(evt) {
        var $group = $("#search-box");
        var isValid = true;
        var count = 0;
        $group.find(':input[type!=button]').each(function(i, item) {
            if (!$(item).valid()) {
                if (isValid == true) {
                    $(item).focus();
                }
                isValid = false;
            }
        });
        if (!isValid)
            evt.preventDefault();
        else {
            var url = "/profile/search?";

            if ($("#SearchGenderMale").is(':checked') || $("#SearchGenderFemale").is(':checked')) {
                if ($("#SearchGenderMale").is(':checked'))
                    url += "gender=1";
                else
                    url += "gender=0";
                count += 1;
            }
            if ($("#SearchCity :selected").val() != -1) {
                if (count > 0) {
                    url += "&";
                }
                url += "city=" + $("#SearchCity :selected").val();
                count += 1;
            }
            if ($("#SearchJob :selected").val() != -1) {
                if (count > 0) {
                    url += "&";
                }
                url += "job=" + $("#SearchJob :selected").val();
                count += 1;
            }
            if ($("#SearchFromAge").val() != "") {
                if (count > 0) {
                    url += "&";
                }
                url += "fromage=" + $("#SearchFromAge").val();
                count += 1;
            }
            if ($("#SearchToAge").val() != "") {
                if (count > 0) {
                    url += "&";
                }
                url += "toage=" + $("#SearchToAge").val();
                count += 1;
            }
            if (count == 0) {
                jAlert(CoditionRequired);
                return;
            }
            var viewType = readCookies(CurrentUserKey + "-searchviewtype");
            if (viewType != null) {
                url += "&viewtype=" + viewType;
            }
            else {
                url += "&viewtype=thumb";
            }
            window.location = url;
        }
    });

    ChangeSearchViewType = function(viewtype) {
        window.location = $("#SearchUrl").val() + "&viewtype=" + viewtype;
        createCookie(CurrentUserKey + "-searchviewtype", viewtype, 365);
    };

    //end: Search

    /*** begin: Messages   ***/

    ShowHideMessage = function(messageID) {
        if ($('#MessageStatus-' + messageID).val() == "show") {
            $('#MessageContent-' + messageID).slideUp("medium"); //hide
            $('#ShortContent-' + messageID).show("fast");
            $('#MessageStatus-' + messageID).val("hide");
        }
        else if ($('#MessageStatus-' + messageID).val() == "hide") {
            $('#MessageContent-' + messageID).slideDown("medium"); //show
            $('#ShortContent-' + messageID).hide("fast");
            $('#MessageStatus-' + messageID).val("show");
        }
    };

    /*** begin: Send  ***/

    SendMessagePopup = function(ReceivedUserKey) {
        if (CurrentUserKey == ReceivedUserKey) {
            jAlert(SendYourselfMessageError);
        }
        else if ($("#CanDoAction").val() == "false") {
            jAlert(VarifiedAccountRequired);
        }
        else {
            Shadowbox.open({
                player: "iframe",
                content: GLOBAL_ROOT_URL + 'profile/sendmessage?ur=' + ReceivedUserKey,
                //title: $(this).attr("title"), 
                height: "320",
                width: "540"
            });
        }
    };

    SendMessageComplete = function(result) {
        if (result == "-1") {
            window.location = "/login";
            return;
        }
        if (result == "-2") {
            jAlert(ReceiverKeyError);
        }
        else if (result == "1") {
            jAlert(SendMessageSuccess);
        }
        Shadowbox.close();
    };

    ClosePopup = function() {
        Shadowbox.close();
    };

    //end: Send

    /*** begin: Delete   ***/

    DeleteConversation = function(conversationId) {
        jConfirm('Bạn muốn xóa cuộc hội thoại?', 'Xác nhận', function(r) {
            if (r) {
                $.ajax({
                    async: false,
                    dataType: 'json',
                    url: "/api/user.ashx",
                    type: 'POST',
                    data: {
                        action: "deleteConversation",
                        conversationId: conversationId
                    },
                    success: function(data) {
                        if (data.result == "-1") {
                            window.location = '/login';
                            return;
                        }
                        else if (data.result == "0") {
                            jAlert(SystemError);
                            return;
                        }
                        window.location = "/profile/messages?viewtype=" + $("#ViewType").val() + "&p=" + $("#Page").val();
                    }
                });
            }
        });
    };

    DeleteMessage = function(messageID, type) {
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/user.ashx",
            type: 'POST',
            data: {
                action: "deleteMessage",
                messageID: messageID,
                delType: type
            },
            success: function(data) {
                if (data.result == "-1") {
                    window.location = '/login';
                    return;
                }
                if (data.result == "2") {
                    jAlert(DeleteArgumentError);
                    return;
                }
                else if (data.result == "0") {
                    jAlert(SystemError);
                    return;
                }
                $("#Message-" + messageID).hide("medium");
            }
        });
    };

    //end: Conversation

    /*** begin: Reply   ***/

    $("#btnReplyMessage").click(function() {
        if ($("#ReplyContent").val() == "") {
            jAlert(ContentMissError);
            return;
        }
        else if ($("#ReplyContent").val().length > MessageContentLimit) {
            jAlert(MessageLengthError);
            return;
        }
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/user.ashx",
            type: 'POST',
            data: {
                action: 'replyMessage',
                conversationID: $("#ConversationID").val(),
                messageContent: $("#ReplyContent").val()
            },

            success: function(data) {
                if (data.result == "-1") {
                    window.parent.location = "/login";
                    return;
                }
                if (data.result == "0") {
                    jAlert(SystemError);
                    return;
                }
                if (data.result == "2") {
                    jAlert(ConversationNotExist);
                    return;
                }
                if (data.result == "3") {
                    jAlert(ContentMissError);
                    return;
                }
                if (data.result == "4") {
                    jAlert(SendMore3MessageError);
                    return;
                }
                if (data.result == "5") {
                    jAlert(ContentNotAppropriateError);
                    return;
                }
                if (data.result == "1") {
                    var domHTML = "";
                    var newID = data.newID;
                    var senderName = data.senderName;
                    var shortContent = data.shortContent;
                    var content = data.Content;
                    var currentTime = new Date();
                    var month = currentTime.getMonth() + 1;
                    var day = currentTime.getDate();
                    var year = currentTime.getFullYear();
                    var hour = currentTime.getHours();
                    var min = currentTime.getMinutes();
                    var sentTime = day + "/" + month + "/" + year + " " + hour + ":" + min;

                    domHTML += ('<div class="message" id="Message-' + newID + '" >');
                    domHTML += ('<input type="hidden" id="MessageStatus-' + newID + '" value="show" />');
                    domHTML += ('<div class="message-header" id="MessageHeader-' + newID + '" onclick="ShowHideMessage(' + newID + ')">');
                    domHTML += ('<div class="name">' + senderName + '</div>');
                    domHTML += ('<div class="short-content">');
                    domHTML += ('<span class="last-short-content" id="ShortContent-' + newID + '">' + shortContent + '</span>&nbsp;');
                    domHTML += ('</div>');
                    domHTML += ('<div class="right">');
                    domHTML += ('<input type="button" class="delete-message" onclick="DeleteMessage(' + "'" + newID + "','" + 's' + "'" + ')" />');
                    domHTML += ('</div>');
                    domHTML += ('</div>');
                    domHTML += ('<div class="content display-content" id="MessageContent-' + newID + '">' + content + '</div>');
                    domHTML += ('</div>');
                    $("#messages").append(domHTML);
                    $("#ReplyContent").val("");
                    $("#ReplyContent").focus();
                }
            }
        });
    });

    //end: Reply Message

    //end: Messages

    //begin: Interest

    ChangeInterestViewType = function(viewtype) {
        if (viewtype == null) {
            viewtype = readCookies(CurrentUserKey + "-interestviewtype");
            if (viewtype == null) {
                window.location = "profile/interest?viewtype=thumb";
            }
            else {
                window.location = "profile/interest?viewtype=" + viewtype;
            }
        }
        else {
            window.location = "interest?viewtype=" + viewtype;
            createCookie(CurrentUserKey + "-interestviewtype", viewtype, 365);
        }
    };

    AddFollow = function(followedUserKey) {
        if ($("#CanDoAction").val() == "false") {
            jAlert(VarifiedAccountRequired);
            return;
        }
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/user.ashx",
            type: 'POST',
            data: {
                action: "addFollow",
                followedUserKey: followedUserKey
            },
            success: function(data) {
                if (data.result == "-1") {
                    window.location = '/login';
                    return;
                }
                else if (data.result == "2") {
                    jAlert(UserNotExist);
                    return;
                }
                else if (data.result == "3") {
                    jAlert(AddYouselfError);
                    return;
                }
                else if (data.result == "4") {
                    jAlert(VarifiedAccountRequired);
                    return;
                }
                else if (data.result == "5") {
                    jAlert(FollowedUserExist);
                    return;
                }
                else if (data.result == "6") {
                    jAlert(FollowLimitError);
                    return;
                }
                else if (data.result == "0") {
                    jAlert(SystemError);
                    return;
                }
                if (data.result == "1") {
                    jAlert(AddFollowSuccess);
                }
            }
        });
    };

    DeleteFollow = function(followedUserKey) {
        jConfirm('Bạn muốn xóa hồ sơ này khỏi danh sách quan tâm?', 'Xác nhận', function(r) {
            if (r) {
                $.ajax({
                    async: false,
                    dataType: 'json',
                    url: "/api/user.ashx",
                    type: 'POST',
                    data: {
                        action: "deleteFollow",
                        followedUserKey: followedUserKey
                    },
                    success: function(data) {
                        if (data.result == "-1") {
                            window.location = '/login';
                            return;
                        }
                        else if (data.result == "2") {
                            jAlert(UserNotExist);
                            return;
                        }
                        else if (data.result == "0") {
                            jAlert(SystemError);
                            return;
                        }
                        if (data.result == "1") {
                            $("#profile-" + followedUserKey).hide("fast");
                            $("#FollowedCount").val(parseInt($("#FollowedCount").val()) - 1);
                            if ($("#FollowedCount").val() == "0") {
                                $("#interested-profile-list").append("<div class='empty'>Bạn chưa có hồ sơ quan tâm</div>");
                            }
                        }
                    }
                });
            }
        });
    };

    //end: Interest

    //begin: Report

    SendReportPopup = function(ReportedUserKey) {
        if ($("#CanDoAction").val() == "false") {
            jAlert(VarifiedAccountRequired);
            return;
        }
        Shadowbox.open({
            player: "iframe",
            content: GLOBAL_ROOT_URL + 'profile/sendreport?ur=' + ReportedUserKey,
            //title: $(this).attr("title"), 
            height: "170",
            width: "390"
        });
    };

    SendReportComplete = function(result) {
        if (result == "-1") {
            window.location = "/login";
            return;
        }
        if (result == "-2") {
            jAlert(ReportedUserKeyError);
        }
        else if (result == "1") {
            jAlert(SendReportSuccess);
        }
        Shadowbox.close();
    };

    //end: Report

    //begin: Comment to Admin

    SendCommentComplete = function(result) {
        if (result == "-1") {
            window.location = "/login";
            return;
        }
        else if (result == "1") {
            jAlert(SendCommentSuccess);
        }
        Shadowbox.close();
    };

    //end: Comment to Admin

    //begin: Noel event
    ChangeNoelEvent = function(value) {
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/events.ashx",
            type: 'POST',
            data: {
                action: "sendNoel",
                goOut: value
            },
            success: function(data) {
                if (data.result == "-1") {
                    window.location = '/login';
                    return;
                }
                else if (data.result == "0") {
                    jAlert(SystemError);
                    return;
                }
                if (data.result == "1") {
                    //$("#noel-event-content").html(data.html);
                    $("#noel-event").hide();
                }
            }
        });
    };

    //end : Noel event

    //Validate For Form ComingSoon
    var ValidateAndSubmitComingSoon = function(evt) {

        // Validate the form and retain the result.
        var $group = $('.comingsoon');
        var isValid = true;
        $group.find(':input[type!=button]').each(function(i, item) {
            if (!$(item).valid()) {
                if (isValid == true)
                    $(item).focus();
                isValid = false;
            }
        });

        if (!isValid)
            evt.preventDefault();
        else {
            $("#btnJoinEmail").hide();
            $("#btnJoinEmail").parent().prepend("<img id=\"ajaxloader\" style=\"padding-top:10px;float:right;\" src=\"" + GLOBAL_RESOURCES_PATH + "/images/ajax-loader.gif\" alt=\"đang tải\" />");
            $.ajax({
                async: false,
                dataType: 'json',
                url: "/api/user.ashx",
                type: 'POST',
                data: {
                    action: "createEmail",
                    email: $("#email_cs").val()
                },
                success: function(data) {
                    window.location = GLOBAL_ROOT_URL + "register?u=" + $("#email_cs").val();
                }
            });
        }
    };

    //Validate For Form Register
    var ValidateAndSubmitRegister = function(evt) {
        // Validate the form and retain the result.
        var $group = $('#register-box');
        var isValid = true;
        $group.find(':input[type!=button]').each(function(i, item) {
            if (!$(item).valid()) {
                if (isValid == true) {
                    $(".tip-twitter").remove();
                    $(item).focus();
                }
                isValid = false;
            }
        });
        $(".tip-twitter").show();
        if (!isValid)
            evt.preventDefault();
        else {
            var refesh = new Date();
            $("#frmmain").attr("action", "/api/user.ashx?" + refesh.getMilliseconds());
            $("#frmmain").attr("method", "post");
            $("#frmmain").attr("target", "UploadWindow");
            $("#frmmain").attr("enctype", "multipart/form-data");
            $("#frmmain").attr("encoding", "multipart/form-data");
            $("#action-request").attr("name", "action");
            //$(this).submit();

            $("#btnSubmit").hide();
            $("#btnSubmit").parent().prepend("<img id=\"ajaxloader\" style=\"padding-top:10px;\" src=\"" + GLOBAL_RESOURCES_PATH + "/images/ajax-loader.gif\" alt=\"đang tải\" />");
            $("#frmmain").submit();
        }
    };

    //Validate For Form Login
    var ValidateAndSubmitLogin = function(evt) {
        // Validate the form and retain the result.
        var $group = $('#login-page');
        var isValid = true;
        $group.find(':input[type!=button]').each(function(i, item) {
            if (!$(item).valid()) {
                if (isValid == true) {
                    $(item).focus();
                }
                isValid = false;
            }
        });

        if (!isValid)
            evt.preventDefault();
        else {
            $("#btnDangNhap").hide();
            $("#btnDangNhap").parent().prepend("<img id=\"ajaxloader\" style=\"padding-top:10px;\" src=\"" + GLOBAL_RESOURCES_PATH + "/images/ajax-loader.gif\" alt=\"đang tải\" />");
            $.ajax({
                async: false,
                dataType: 'json',
                url: "/api/user.ashx",
                type: 'POST',
                data: {
                    action: "login",
                    username: $("#email_login").val(),
                    password: $("#password").val(),
                    url: $("#Url").val()
                },
                success: function(data) {
                    if (data.result == "2")
                        jAlert(AccountNotExist);
                    else if (data.result == "3")
                        jAlert(WrongPassword);
                    else if (data.result == "5")
                        jAlert(AccountBlocked);
                    else if (data.result == "6")
                        jAlert(AccountDeleted);
                    else if (data.result == "1")
                        window.location = data.content;
                    else if (data.result == "7")
                        jAlert(SystemError);
                }
            });
            $("#email_login").focus();
            $("#password").val("");
            $("#btnDangNhap").show();
            $("#ajaxloader").remove();
        }
    };

    //Validate For Form Edit General
    var ValidateAndSubmitGeneral = function(evt) {
        var $group = $('#account-box-edit');
        var isValid = true;
        // Descending from that .validationGroup element, find any input
        //  elements within it, iterate over them, and run validation on
        //  each of them.
        $group.find(':input').each(function(i, item) {
            if (!$(item).valid()) {
                if (isValid == true)
                    $(item).focus();
                isValid = false;
            }
        });

        if (!isValid)
            evt.preventDefault();
        else {
            var sex;
            if ($("#EditSexMale").is(":checked") == true) {
                sex = 1;
            }
            else {
                sex = 0;
            }
            $.ajax({
                async: false,
                dataType: 'json',
                url: "/api/user.ashx",
                type: 'POST',
                data: {
                    action: 'saveGeneral',
                    fullName: $("#EditFullName").val(),
                    sex: sex,
                    birthday: $("#EditBirthday").val(),
                    cityID: $("#EditCity :selected").val()
                },
                success: function(data) {
                    if (data.result == "-1")
                        jAlert(LoginRequired);
                    else if (data.result == "2")
                        jAlert(LeakInfoError);
                    else if (data.result == "3")
                        jAlert(FullNameMinError);
                    else if (data.result == "4")
                        jAlert(SexError);
                    else if (data.result == "5")
                        jAlert(BirthdayFormatError);
                    else if (data.result == "6")
                        jAlert(BirthdayError);
                    else if (data.result == "7")
                        jAlert(CityError);
                    else if (data.result == "0")
                        jAlert(SystemError);
                    else {
                        $("#FullName").html($("#EditFullName").val());
                        //Change the full name on header bar
                        $("#header-bar-FullName").html($("#EditFullName").val());
                        if ($("#EditSexMale").is(":checked")) {
                            $("#Sex").html("Nam");
                        }
                        else {
                            $("#Sex").html("Nữ");
                        }
                        var formatDateString = formatDate($("#EditBirthday").val(), "mm/dd/yyyy");
                        $("#Age").html((new Date().getFullYear()) - (new Date(formatDateString).getFullYear()));
                        $("#City").html($("#EditCity :selected").text());
                        $("#account-box").show();
                        $("#account-box-edit").hide();
                    }
                }
            });
        }
    };

    //Validate For Form Personal
    var ValidateAndSubmitPersonal = function(evt) {
        var $group = $('#personal-edit');
        var isValid = true;
        // Descending from that .validationGroup element, find any input
        //  elements within it, iterate over them, and run validation on
        //  each of them.
        $group.find(':input').each(function(i, item) {
            if (!$(item).valid()) {
                if (isValid == true)
                    $(item).focus();
                isValid = false;
            }
        });

        if (!isValid)
            evt.preventDefault();
        else {

            $.ajax({
                async: false,
                dataType: 'json',
                url: "/api/user.ashx",
                type: 'POST',
                data: {
                    action: 'savePersonal',
                    height: $("#txtHeight").val(),
                    weight: $("#txtWeight").val(),
                    religionID: $("#Religion").val(),
                    jobID: $("#Job").val(),
                    educationID: $("#Education").val(),
                    inCome: $("#Income").val(),
                    maritalStatusID: $("#MaritalStatus").val(),
                    smokingID: $("#Smoking").val(),
                    iWantMale: $("#IwantMale").val(),
                    iWantFemale: $("#IwantFemale").val(),
                    hobby: $("#txtHobby").val()
                },
                success: function(data) {
                    if (data.result == "-1")
                        jAlert(LoginRequired);
                    else if (data.result == "2")
                        jAlert(LeakInfoError);
                    else if (data.result == "3")
                        jAlert(HeightWeighError);
                    else if (data.result == "4")
                        jAlert(HeightError);
                    else if (data.result == "5")
                        jAlert(WeightError);
                    else if (data.result == "6")
                        jAlert(HobbyLengthError);
                    else if (data.result == "7")
                        jAlert(IncomeError);
                    else if (data.result == "8")
                        jAlert(EducationError);
                    else if (data.result == "9")
                        jAlert(JobError);
                    else if (data.result == "10")
                        jAlert(ReligionError);
                    else if (data.result == "11")
                        jAlert(SmokingError);
                    else if (data.result == "12")
                        jAlert(MaritalStatusError);
                    else if (data.result == "14")
                        jAlert(HobbyNotAppropriateError);
                    else if (data.result == "1") {
                        $("#field-height").html(ConvertCmToMet($("#txtHeight").val(), true));
                        $("#field-weight").html($("#txtWeight").val() + " Kg");
                        $("#field-religion").html($("#Religion option:selected").text());
                        $("#field-job").html($("#Job option:selected").text());
                        $("#field-education").html($("#Education option:selected").text());
                        if ($("#Income :selected").val() == "0")
                            $("#field-income").html($("#Income :selected").text());
                        else
                            $("#field-income").html("trên " + $("#Income option:selected").text() + " VNĐ");
                        $("#field-marital").html($("#MaritalStatus option:selected").text());
                        $("#field-smoking").html($("#Smoking option:selected").text());
                        if ($("#IwantMale").val() == "1" && $("#IwantFemale").val() == "1")
                            $("#field-iwant").html(IwantAllMsg);
                        else if ($("#IwantMale").val() == "1")
                            $("#field-iwant").html(IwantMaleMsg);
                        else if ($("#IwantFemale").val() == "1")
                            $("#field-iwant").html(IwantFemaleMsg);
                        $("#field-hobby").html($("#txtHobby").val());
                        $("#personal-field").show();
                        $("#personal-edit").hide();
                    }
                    else if (data.result == "0")
                        jAlert(SystemError);
                }
            });
        }
    };

    //Validate For Form General Condition
    var ValidateAndSubmitGeneralCondition = function(evt) {
        var $group = $('#general-condition-edit-fields'); ;
        var isValid = true;
        $group.find(':input').each(function(i, item) {
            if ($(item).attr("type") != "checkbox" && !$(item).valid()) {
                if (isValid == true)
                    $(item).focus();
                isValid = false;
            }
        });

        if (!isValid)
            evt.preventDefault();
        else {

            var minAge, maxAge;
            var minHeight, maxHeight;
            var minWeight, maxWeight;

            if ($("#txtOldMin").val() == "" && $("#txtOldMax").val() == "") {
                minAge = maxAge = 0;
            }
            else if ($("#txtOldMin").val() != "" && $("#txtOldMax").val() != "" &&
                    parseInt($("#txtOldMin").val()) > parseInt($("#txtOldMax").val())) {
                jAlert(MaxMinAgeError);
                return;
            }
            else {
                minAge = $("#txtOldMin").val();
                maxAge = $("#txtOldMax").val();
            }

            if ($("#txtHeightMin").val() == "" && $("#txtHeightMax").val() == "") {
                minHeight = maxHeight = 0;
            }
            else if ($("#txtHeightMin").val() != "" && $("#txtHeightMax").val() != "" &&
                    parseInt($("#txtHeightMin").val()) > parseInt($("#txtHeightMax").val())) {
                jAlert(MaxMinHeightError);
                return;
            }
            else {
                minHeight = $("#txtHeightMin").val();
                maxHeight = $("#txtHeightMax").val();
            }

            if ($("#txtWeightMin").val() == "" && $("#txtWeightMax").val() == "") {
                minWeight = maxWeight = 0;
            }
            else if ($("#txtWeightMin").val() != "" && $("#txtWeightMax").val() != "" &&
                    parseInt($("#txtWeightMin").val()) > parseInt($("#txtWeightMax").val())) {
                jAlert(MaxMinWeightError);
                return;
            }
            else {
                minWeight = $("#txtWeightMin").val();
                maxWeight = $("#txtWeightMax").val();
            }

            $.ajax({
                async: false,
                dataType: 'json',
                url: "/api/user.ashx",
                type: 'POST',
                data: {
                    action: 'saveGeneralCondition',
                    minOld: minAge,
                    maxOld: maxAge,
                    minHeight: minHeight,
                    maxHeight: maxHeight,
                    minWeight: minWeight,
                    maxWeight: maxWeight,
                    cityID: $("#CoditionCity-1").val(),
                    jobID: $("#CoditionJob-1").val(),
                    educationID: $("#CoditionEducation").val(),
                    inCome: $("#CoditionIncome").val(),
                    religionID: $("#CoditionReligion").val(),
                    maritalStatusID: $("#CoditionMaritalStatus").val(),
                    smokingID: $("#CoditionSmoking").val()
                },
                success: function(data) {
                    if (data.result == "-1")
                        jAlert(LoginRequired);
                    else if (data.result == "2")
                        jAlert(MaxMinAgeError);
                    else if (data.result == "3")
                        jAlert(MaxMinHeightError);
                    else if (data.result == "4")
                        jAlert(MaxMinWeightError);
                    else if (data.result == "0")
                        jAlert(SystemError);
                    else if (data.result == "1") {
                        var dontCare = "Không quan tâm";

                        if (minAge == 0 && maxAge == 0) {
                            $("#field-condition-old").html(dontCare);
                        }
                        else {
                            if (minAge == 0 && maxAge > 0) {
                                $("#field-condition-old").html("từ " + maxAge + " tuổi trở xuống");
                            }
                            else if (minAge > 0 && maxAge == 0) {
                                $("#field-condition-old").html("từ " + minAge + " tuổi trở lên");
                            }
                            else {
                                $("#field-condition-old").html("Từ " + minAge + " đến " + maxAge + " tuổi");
                            }
                        }

                        if (minHeight == 0 && maxHeight == 0) {
                            $("#field-condition-height").html(dontCare);
                        }
                        else {
                            if (minHeight == 0 && maxHeight > 0) {
                                $("#field-condition-height").html("Từ " + ConvertCmToMet(maxHeight, true) + " trở xuống");
                            }
                            else if (minHeight > 0 && maxHeight == 0) {
                                $("#field-condition-height").html("Từ " + ConvertCmToMet(minHeight, true) + " trở lên");
                            }
                            else {
                                $("#field-condition-height").html("Từ " + ConvertCmToMet(minHeight, true) + " đến " + ConvertCmToMet(maxHeight, true));
                            }
                        }

                        if (minWeight == 0 && maxWeight == 0) {
                            $("#field-condition-weight").html(dontCare);
                        }
                        else {
                            if (minWeight == 0 && maxWeight > 0) {
                                $("#field-condition-weight").html("Từ " + maxWeight + " Kg trở xuống");
                            }
                            else if (minWeight > 0 && maxWeight == 0) {
                                $("#field-condition-weight").html("Từ " + minWeight + " Kg trở lên");
                            }
                            else {
                                $("#field-condition-weight").html("Từ " + minWeight + " đến " + maxWeight + " Kg");
                            }
                        }

                        if ($("#CoditionIncome :selected").val() == "-1") {
                            $("#field-condition-income").html(dontCare);
                        }
                        else {
                            $("#field-condition-income").html("trên " + $("#CoditionIncome :selected").text() + " VNĐ");
                        }

                        if ($("#CoditionCity-1 :selected").val() == "-1") {
                            $("#field-condition-city").html(dontCare);
                        }
                        else {
                            $("#field-condition-city").html($("#CoditionCity-1 :selected").text());
                        }
                        if ($("#CoditionJob-1 :selected").val() == "-1") {
                            $("#field-condition-job").html(dontCare);
                        }
                        else {
                            $("#field-condition-job").html($("#CoditionJob-1 :selected").text());
                        }
                        if ($("#CoditionEducation :selected").val() == "-1") {
                            $("#field-condition-education").html(dontCare);
                        }
                        else {
                            $("#field-condition-education").html($("#CoditionEducation :selected").text());
                        }
                        if ($("#CoditionReligion :selected").val() == "-1") {
                            $("#field-condition-religion").html(dontCare);
                        }
                        else {
                            $("#field-condition-religion").html($("#CoditionReligion :selected").text());
                        }
                        if ($("#CoditionMaritalStatus :selected").val() == "-1") {
                            $("#field-condition-maritalStatus").html(dontCare);
                        }
                        else {
                            $("#field-condition-maritalStatus").html($("#CoditionMaritalStatus :selected").text());
                        }
                        if ($("#CoditionSmoking :selected").val() == "-1") {
                            $("#field-condition-smoking").html(dontCare);
                        }
                        else {
                            $("#field-condition-smoking").html($("#CoditionSmoking :selected").text());
                        }

                        $("#general-condition-edit").hide();
                        $("#general-condition-field").show();
                    }
                }
            });
        }
    };

    //Add method for validate FullName
    var fullname_title_reg = $("#Fullname").attr("title");
    jQuery.validator.addMethod("checkFullName", function(value, element) {
        if ($("#Fullname").val() == hintFullName) {
            hintFullName = "";
            $("#Fullname").val("");
            return false;
        }
        var strValidChars = "0123456789-_@.";
        for (i = 0; i < value.length; i++) {
            if (strValidChars.indexOf(value.charAt(i)) > -1)
                return false;
        }
        $("#Fullname").attr("title", fullname_title_reg);
        return true;
    }, FullNameError);

    //Add method for validate EditFullName
    var edit_fullname_title_reg = $("#EditFullname").attr("title");
    jQuery.validator.addMethod("checkEditFullName", function(value, element) {
        if ($("#EditFullname").val() == hintFullName) {
            hintFullName = "";
            $("#EditFullname").val("");
            return false;
        }
        var strValidChars = "0123456789-_@.";
        for (i = 0; i < value.length; i++) {
            if (strValidChars.indexOf(value.charAt(i)) > -1)
                return false;
        }
        $("#EditFullname").attr("title", edit_fullname_title_reg);
        return true;
    }, FullNameError);

    //Add method for validate Birthday
    var bir_title_reg = $("#Birthday").attr("title");
    jQuery.validator.addMethod("checkBithday", function(value, element) {
        if ($("#Birthday").val() == hintBirthday) {
            hintBirthday = "";
            $("#Birthday").val("");
            return false;
        }

        var birthdayYear = new Date(formatDate($("#Birthday").val(), "mm/dd/yyyy")).getFullYear();
        if (ValidateFormDate($("#Birthday").val()) == false || EndDate.getFullYear() < birthdayYear || BeginDate.getFullYear() > birthdayYear)
            return false;
        $("#Birthday").attr("title", bir_title_reg);
        return true;
    }, BirthdayError);

    //Add method for validate EditBirthday
    var edit_bir_title_reg = $("#EditBirthday").attr("title");
    jQuery.validator.addMethod("checkEditBirthday", function(value, element) {
        if ($("#EditBirthday").val() == hintBirthday) {
            hintBirthday = "";
            $("#EditBirthday").val("");
            return false;
        }

        var birthdayYear = new Date(formatDate($("#EditBirthday").val(), "mm/dd/yyyy")).getFullYear();
        if (ValidateFormDate($("#EditBirthday").val()) == false || EndDate.getFullYear() < birthdayYear || BeginDate.getFullYear() > birthdayYear)
            return false;
        $("#EditBirthday").attr("title", edit_bir_title_reg);
        return true;
    }, BirthdayError);

    //Add method for validate I Want
    var iwant_title_reg = $("#IwantMale").attr("title");
    jQuery.validator.addMethod("checkIWant", function(value, element) {
        if ($('#IwantMale').is(':checked') || $('#IwantFemale').is(':checked')) {
            $(".groupIWant").css("border", "none");
            $(".groupIWant").css("border-left", "none");
            $(".groupIWant").css("padding-left", "0px");
            return true;
        }
        $("#IwantMale").attr("title", iwant_title_reg);
        $("#IwantFemale").attr("title", iwant_title_reg);
        $("#spanIWant").attr("title", iwant_title_reg);
        $(".groupIWant").css("border", "1px solid #E90037");
        $(".groupIWant").css("border-left", "2px solid #E90037");
        $(".groupIWant").css("padding-left", "1px");
        return false;
    }, IwantRequired);

    //Add method for validate Sex
    var sex_title_reg = $("#SexMale").attr("title");
    jQuery.validator.addMethod("checkSex", function(value, element) {
        if ($('#SexMale').is(':checked') || $('#SexFemale').is(':checked')) {
            $(".groupSex").css("border", "none");
            return true;
        }
        $("#SexMale").attr("title", sex_title_reg);
        $("#SexFemale").attr("title", sex_title_reg);
        $(".groupSex").css("border", "1px solid #E90037");
        return false;
    }, SexRequired);

    //Add method for validate EditSex
    var edit_sex_title_reg = $("#EditSexMale").attr("title");
    jQuery.validator.addMethod("checkEditSex", function(value, element) {
        if ($('#EditSexMale').is(':checked') || $('#EditSexFemale').is(':checked')) {
            $(".groupSex").css("border", "none");
            return true;
        }
        $("#EditSexMale").attr("title", sex_title_reg);
        $("#EditSexFemale").attr("title", sex_title_reg);
        $(".groupSex").css("border", "1px solid #E90037");
        return false;
    }, SexRequired);


    //Add method for validate Email
    var email_title = $("#email_login").attr("title");
    jQuery.validator.addMethod("checkEmail", function(value, element) {
        if (this.optional(element))
            return true;
        if (!(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value)))
            return false;
        var strValidChars = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM-_@.";
        for (i = 0; i < value.length; i++) {
            if (strValidChars.indexOf(value.charAt(i)) < 0)
                return false;
        }
        $("#email_login").attr("title", email_title);
        return true;
    }, EmailError);

    //Add method for validate Phone
    var phone_title_reg = $("#Phone").attr("title");
    jQuery.validator.addMethod("checkPhone", function(value, element) {
        //  check for valid numeric strings
        var strValidChars = "0123456789";
        var strChar;
        var blnResult = true;
        //  test strString consists of valid characters listed above
        value = value.replace(" ", "");
        value = value.replace(".", "");
        value = value.replace("-", "");
        value = value.replace("_", "");
        value = value.replace("(", "");
        value = value.replace(")", "");
        if (value.length > 0 && (value.length < 10 || value.length > 20))
            return false;
        for (i = 0; i < value.length && blnResult == true; i++) {
            strChar = value.charAt(i);
            if (strValidChars.indexOf(strChar) == -1) {
                blnResult = false;
            }
        }
        $("#Phone").attr("title", phone_title_reg);
        return blnResult;
    }, MobilePhoneError);

    //Add method for validate Search Age
    jQuery.validator.addMethod("checkSearchAge", function(value, element) {
        if ($(element).val() == "") {
            return true;
        }
        if (parseInt($(element).val()) < MinAge || parseInt($(element).val()) > MaxAge) {
            return false;
        }
        return true;
    }, AgeError);

    //Add method for validate Condition Age Min
    var ageMin_title = $("#txtOldMin").attr("title");
    jQuery.validator.addMethod("checkAgeMin", function(value, element) {

        if ($(element).val() == "") {
            return true;
        }
        if (parseInt($(element).val()) < MinAge || parseInt($(element).val()) > MaxAge) {
            return false;
        }
        $(element).attr("title", ageMin_title);
        return true;
    }, AgeError);

    //Add method for validate Condition Age Max
    var ageMax_title = $("#txtOldMax").attr("title");
    jQuery.validator.addMethod("checkAgeMax", function(value, element) {
        if ($(element).val() == "") {
            return true;
        }
        if (parseInt($(element).val()) < MinAge || parseInt($(element).val()) > MaxAge) {
            return false;
        }
        $(element).attr("title", ageMax_title);
        return true;
    }, AgeError);

    //Add method for validate Condition Height Min
    var heightMin_title = $("#txtHeightMin").attr("title");
    jQuery.validator.addMethod("checkHeightMin", function(value, element) {
        if ($(element).val() == "") {
            return true;
        }
        if (parseInt($(element).val()) < HeightMin || parseInt($(element).val()) > HeightMax) {
            return false;
        }
        $(element).attr("title", heightMin_title);
        return true;
    }, HeightError);

    //Add method for validate Condition Height Max
    var heightMax_title = $("#txtHeightMax").attr("title");
    jQuery.validator.addMethod("checkHeightMax", function(value, element) {
        if ($(element).val() == "") {
            return true;
        }
        if (parseInt($(element).val()) < HeightMin || parseInt($(element).val()) > HeightMax) {
            return false;
        }
        $(element).attr("title", heightMax_title);
        return true;
    }, HeightError);

    //Add method for validate Condition Weight Min
    var weightMin_title = $("#txtWeightMin").attr("title");
    jQuery.validator.addMethod("checkWeightMin", function(value, element) {
        if ($(element).val() == "") {
            return true;
        }
        if (parseInt($(element).val()) < WeightMin || parseInt($(element).val()) > WeightMax) {
            return false;
        }
        $(element).attr("title", weightMin_title);
        return true;
    }, WeightError);

    //Add method for validate Condition Weight Max
    var weightMax_title = $("#txtWeightMin").attr("title");
    jQuery.validator.addMethod("checkWeightMax", function(value, element) {
        if ($(element).val() == "") {
            return true;
        }
        if (parseInt($(element).val()) < WeightMin || parseInt($(element).val()) > WeightMax) {
            return false;
        }
        $(element).attr("title", weightMin_title);
        return true;
    }, WeightError);

    //Add method for validate Number
    jQuery.validator.addMethod("checkForNumber", function(value, element) {
        if (this.optional(element)) {
            return true;
        }
        if (!(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value))) {
            return false;
        }
        return true;
    }, NumberError);

    //Define General Rule For Form
    Valid = $("#frmmain").validate({
        errorPlacement: function(error, element) {
            //$(element).poshytip({refresh: true,showOn: 'none'});
            //$(element).poshytip('enable');
            $(element).attr("title", $(error).html());

            /*$(element).poshytip("destroy");
            $(element).poshytip({
            content: $(error).html(),
            showOn: 'none'
            });*/
            $(".tip-twitter").show();
        },
        errorClass: "field-error",
        errorElement: "div",
        unhighlight: function(element, errorClass, validClass) {
            //$(element).attr("title","");
            $(element).removeClass(errorClass).addClass(validClass);
            $(".tip-twitter").hide();

            //$(element).poshytip('disable');
            $(element).poshytip({ refresh: true, showOn: 'none' });
        },
        rules: {
            //ComingSoon
            email_cs: {
                required: true,
                checkEmail: true
            },
            accept: "required",
            //Register
            Fullname: {
                required: true,
                minlength: 6,
                checkFullName: true
            },
            Sex: {
                checkSex: true
            },
            IwantMale: {
                checkIWant: true
            },
            IwantFemale: {
                checkIWant: true
            },
            Birthday: {
                required: true,
                checkBithday: true
            },
            City: "required",
            Job: "required",
            Email: {
                required: true,
                checkEmail: true
            },
            VerifyEmail: {
                required: true,
                equalTo: "#Email"
            },
            Phone: {
                checkPhone: true
            },
            //General
            EditFullname: {
                required: true,
                minlength: 6,
                checkEditFullName: true
            },
            EditBirthday: {
                required: true,
                checkEditBirthday: true
            },
            EditSex: {
                checkEditSex: true
            },
            EditCity: "required",
            //Personal
            txtHeight:
            {
                required: true,
                number: true,
                min: HeightMin,
                max: HeightMax
            },
            txtWeight:
            {
                required: true,
                number: true,
                min: WeightMin,
                max: WeightMax
            },
            Religion: "required",
            Job: "required",
            Education: "required",
            Income:
            {
                required: true
                //number: true
            },
            MaritalStatus: "required",
            Smoking: "required",
            IwantMale: {
                checkIWant: true
            },
            IwantFemale: {
                checkIWant: true
            },
            txtHobby: "required",
            //Login
            email_login:
            {
                required: true,
                checkEmail: true
            },
            password: "required",
            //General Condition
            txtHeightMin:
            {
                checkForNumber: true,
                checkHeightMin: true
            },
            txtHeightMax:
            {
                checkForNumber: true,
                checkHeightMax: true
            },
            txtWeightMin:
            {
                checkForNumber: true,
                checkWeightMin: true
            },
            txtWeightMax:
            {
                checkForNumber: true,
                checkWeightMax: true
            },
            txtOldMin:
            {
                checkForNumber: true,
                checkAgeMin: true
            },
            txtOldMax:
            {
                checkForNumber: true,
                checkAgeMax: true
            },
            //ContactInfo
            txtEmail:
            {
                checkEmail: true
            },
            txtHomePhone:
            {
                checkForNumber: true
            },
            txtMobile:
            {
                checkForNumber: true
            },
            NewPassword:
            {
                required: true,
                minlength: 6,
                maxlength: 32
            },
            ConfirmNewPassword: {
                required: true,
                equalTo: "#NewPassword"

            },

            //Search
            SearchFromAge:
            {
                checkForNumber: true,
                checkSearchAge: true
            },
            SearchToAge:
            {
                checkForNumber: true,
                checkSearchAge: true
            }
        },
        messages: {
            //ComingSoon
            email_cs: {
                required: EmailRequired,
                checkEmail: EmailError
            },
            accept: hintAccept,
            //For Register
            Fullname: {
                required: FullNameError,
                checkFullName: FullNameError,
                minlength: FullNameMinError
            },
            Sex: {
                checkSex: SexRequired
            },
            IwantMale: {
                checkIWant: IwantRequired
            },
            IwantFemale: {
                checkIWant: IwantRequired
            },
            Birthday: {
                required: BirthdayRequired,
                checkBithday: BirthdayError
            },
            City: CityRequired,
            Job: JobRequired,
            Email: {
                required: EmailRequired,
                checkEmail: EmailError
            },
            VerifyEmail: {
                required: ConfirmEmailRequired,
                equalTo: ConfirmEmailError
            },
            Phone: {
                checkPhone: MobilePhoneError
            },
            //For General
            EditFullName: {
                required: FullNameError,
                checkEditFullName: FullNameError,
                minlength: FullNameMinError
            },
            EditSex: {
                checkEditSex: SexRequired
            },
            EditBirthday: {
                required: BirthdayRequired,
                checkEditBirthday: BirthdayError
            },
            EditCity: CityRequired,
            //For Personal
            txtHeight:
            {
                required: HeightRequired,
                number: HeightTypeError,
                min: HeightMinError,
                max: HeightMaxError
            },
            txtWeight:
            {
                required: WeightRequired,
                number: WeightTypeError,
                min: WeightMinError,
                max: WeightMaxError
            },
            Religion: "Bạn hãy cho biết tôn giáo của bạn.",
            Job: "Bạn hãy cho biết nghề nghiệp của bạn.",
            Education: "Bạn hãy cho biết học vấn của bạn.",
            Income:
            {
                required: IncomeRequired
            },
            MaritalStatus: "Bạn hãy chọn biết tình trạnh hôn nhân.",
            Smoking: "Bạn có hút thuốc không?",
            IwantMale: {
                checkIWant: "Bạn hãy cho biết giới tính mà bạn quan tâm."
            },
            IwantFemale: {
                checkIWant: "Bạn hãy cho biết giới tính mà bạn quan tâm."
            },
            txtHobby: HobbyRequired,
            //For Login
            email_login: {
                required: EmailRequired,
                checkEmail: EmailError
            },
            password: PasswordRequired,
            //For General Condition
            txtOldMin: {
                checkForNumber: AgeTypeError,
                checkAgeMin: AgeError
            },
            txtOldMax: {
                checkForNumber: AgeTypeError,
                checkAgeMax: AgeError
            },
            txtHeightMin:
            {
                checkForNumber: HeightTypeError,
                checkHeightMin: HeightError
            },
            txtHeightMax:
            {
                checkForNumber: HeightTypeError,
                checkHeightMax: HeightError
            },
            txtWeightMin:
            {
                checkForNumber: WeightTypeError,
                checkWeightMin: WeightError
            },
            txtWeightMax:
            {
                checkForNumber: WeightTypeError,
                checkWeightMax: WeightError
            },
            //For Contact Info
            txtEmail:
            {
                checkEmail: EmailError
            },
            txtMobile:
            {
                checkForNumber: NumberError
            },
            txtHomePhone:
            {
                checkForNumber: NumberError
            },

            NewPassword: {
                required: NewPasswordMissError,
                minlength: PasswordLengthError,
                maxlength: PasswordLengthError
            },
            ConfirmNewPassword: {
                required: ReTypePasswordMissError,
                checkConfirmNewPassword: ReTypePassMissMatchError
            },

            //For Search
            SearchFromAge: {
                checkForNumber: AgeTypeError,
                checkSearchAge: AgeError
            },
            SearchToAge: {
                checkForNumber: AgeTypeError,
                checkSearchAge: AgeError
            }
        }
    });

    //end: Validate For Form
});

var getParam = function(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
};

var ConvertCmToMet = function(value, hasUnit) {
    var met = parseInt(value) / 100;
    var cm = parseInt(value) - parseInt(met) * 100;
    if (hasUnit == true) {
        if (cm < 10) {
            return Math.floor(met) + ".0" + cm + "m";
        }
        return Math.floor(met) + "." + cm + "m";
    }
    if (cm < 10) {
        return Math.floor(met) + ".0" + cm;
    }
    return Math.floor(met) + "." + cm;
};

// This is validate for only login and register
$("#frmmain").validate({
    errorPlacement: function(error, element) {
        $(element).poshytip({ refresh: true, showOn: 'none' });
        $(element).poshytip('enable');
        $(element).attr("title", $(error).html());

        $(element).poshytip("destroy");
        $(element).poshytip({
            content: $(error).html(),
            showOn: 'none'
        });
        $(".tip-twitter").show();
    }
});

createCookie = function(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
};

readCookies = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0 || c.indexOf(name) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
};
